package com.fastfood.model.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.fastfood.model.dto.FoodType;

public class FoodTypeDAO {
	
	public boolean addFoodType(Connection conn, FoodType foodType) {
		String query = "insert into food_types (name, description) values (?, ?)";
		boolean result = false;
		try {
			PreparedStatement preparedStatement = conn.prepareStatement(query);
			preparedStatement.setString(1, foodType.getName());
			preparedStatement.setString(2, foodType.getDescription());
			preparedStatement.executeUpdate();
			result = true;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}

	public boolean deleteFoodType(Connection conn, FoodType foodType) {
		String query = "delete from food_types where id = ?";
		boolean result = false;
		try {
			PreparedStatement preparedStatement = conn.prepareStatement(query);
			preparedStatement.setInt(1, foodType.getId());
			preparedStatement.executeUpdate();
			result = true;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public boolean updateFoodType(Connection conn, FoodType foodType) {
		String query = "update food_types set name = ?, description = ? where id = ?";
		boolean result = false;
		try {
			PreparedStatement preparedStatement = conn.prepareStatement(query);
			preparedStatement.setString(1, foodType.getName());
			preparedStatement.setString(2, foodType.getDescription());
			preparedStatement.setInt(3, foodType.getId());
			preparedStatement.executeUpdate();
			result = true;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public FoodType getFoodTypeById(Connection conn, int id) {
		FoodType foodType = null;
		try {
			ResultSet result = conn.createStatement().executeQuery("select * from food_types where id = " + id);
			if (result.next()) {
				foodType = new FoodType();
				foodType.setId(result.getInt("id"));
				foodType.setName(result.getString("name"));
				foodType.setDescription(result.getString("description"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return foodType;
	}
	
	public List<FoodType> getAllFoodTypes(Connection conn) {
		List<FoodType> foodTypes = null;
		try {
			ResultSet result = conn.createStatement().executeQuery("select * from food_types");
			foodTypes = new ArrayList<FoodType>();
			while (result.next()) {
				FoodType temp = new FoodType();
				temp.setId(result.getInt("id"));
				temp.setName(result.getString("name"));
				temp.setDescription(result.getString("description"));
				
				foodTypes.add(temp);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return foodTypes;
	}
}
